package com.nhc.activity_fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.astrob.activitys.AppContext;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.manager.DBDataCenter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.ShowPictureActivity;
import zuo.biao.library.ui.TopMenuWindow;
import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.ImageLoaderUtil;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.StringUtil;

public class PhotoAlbumActivity extends BaseActivity implements AlertDialog.OnDialogButtonClickListener {
    private final String TAG = "SelectIconActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    public static final String INTENT_PHOTOALBUM_SELECT = "INTENT_PHOTOALBUM_SELECT";

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, PhotoAlbumActivity.class);
    }

    public static Intent createIntentSelect(Context context) {
        return new Intent(context, PhotoAlbumActivity.class)
                .putExtra(INTENT_PHOTOALBUM_SELECT, true);
    }
    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    boolean _onlyselect = false;

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photoalbum_activity);

        intent = getIntent();
        _onlyselect = intent.getBooleanExtra(INTENT_PHOTOALBUM_SELECT, _onlyselect);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private GridView lvPhoneGird;
    private Button bt_pic_do;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE

        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        lvPhoneGird = (GridView) findViewById(R.id.lvPhoneGird);

        bt_pic_do = (Button) findViewById(R.id.bt_pic_do);

        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        if (_onlyselect) {
            findViewById(R.id.iv_rightmenu).setVisibility(View.GONE);
        }
    }

    //示例代码<<<<<<<<
    private GridAdapter adapter;
    //示例代码>>>>>>>>

    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new GridAdapter(context);
            lvPhoneGird.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> list;

    protected List<Entry<Integer, String>> getList() {
        list = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < picFilelist.size(); i++) {
            list.add(new Entry<Integer, String>(i, ""));
        }
        return list;
    }

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreateView方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        picFilelist.clear();
        showProgressDialog(R.string.loading);

        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
//                if (SysUtils.getInstance().is240x320) {
//                    seachPic(Environment.getExternalStorageDirectory() + "/PIC/");
//                } else {
//                    seachPic(EXDIR0);
//                    seachPic(EXDIR1);
//                }
//                Utils.deleteAllFiles(new File(Environment.getExternalStorageDirectory()+"/DCIM/"));
                seachPic(Environment.getExternalStorageDirectory() + "/DCIM/");

                list = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(list);
                    }
                });
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用
        lvPhoneGird.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                doFounc(adapter.getItem(position).getKey());
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    private void doFounc(Integer gridIndex) {

        if (mIsEdit && null != hashMap) {
            boolean isSelected = hashMap.get(gridIndex);
            hashMap.put(gridIndex, !isSelected);
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }

            boolean haveselected = false;
            for (int i = 0; i < picFilelist.size(); i++) {
                if (hashMap.get(i)) {
                    haveselected = true;
                    break;
                }
            }
            if (haveselected) {
                bt_pic_do.setText(getString(R.string.delete));
            } else {
                bt_pic_do.setText(getString(R.string.cancel));
            }

        } else {
            _select = gridIndex;
            adapter.notifyDataSetChanged();
            String picturePath = picFilelist.get(gridIndex);
            if (StringUtil.isFilePath(picturePath) != false) {
                boolean haveNavi = false;
                LonLat ll = Utils.getExifLonLat(picturePath);
                if (ll.IsValid()) {
                    haveNavi = true;
                }

                if (_onlyselect) {
                    setResult(RESULT_OK, new Intent().putExtra(RESULT_PICTURE_PATH, picturePath));
                    finish();
                } else {
                    toActivity(ShowPictureActivity.createIntent2(context, picturePath, haveNavi), 0);
                }

            }
        }


    }

    public static final String RESULT_PICTURE_PATH = "RESULT_PICTURE_PATH";

    @Override
    public void onForwardClick(View v) {
        //top栏右边按钮响应

        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_photo)), REQUEST_TO_TOP_MENU, false);
    }

    @Override
    public void onReturnClick(View v) {
        setResult(-1);
        finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            default:
                adapter.notifyDataSetChanged();
                break;
            case KeyEvent.KEYCODE_BACK:
                setResult(-1);
                finish();
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    private final int REQUEST_TO_TOP_MENU = 30;
    private final int REQUEST_CODE_CAMERA = 18;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Msg.NAVI_TO_DEST) {
            if (_select >= 0 && _select < picFilelist.size()) {
                LonLat ll = Utils.getExifLonLat(picFilelist.get(_select));
                if (ll.IsValid()) {
                    DBDataCenter.getInstance().makerNavi = new WayPoint();
                    DBDataCenter.getInstance().makerNavi.setLL(ll);
                    DBDataCenter.getInstance().routeNavi = null;
                    DBDataCenter.getInstance().wayTrailNavi = null;
                    setResult(Msg.NAVI_TO_DEST);
                    finish();
                } else {
                    showShortToast(getString(R.string.czpmyjwd));
                }
            }

            return;
        }

        if (requestCode == REQUEST_TO_TOP_MENU) {
            if (data != null) {
                switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                    case 0:
                        selectPicFromCamera();
                        break;
                    case 1:
                        onToEdit();
                        break;
                    default:
                        break;
                }
            }
        } else if (requestCode == REQUEST_CODE_CAMERA) {
            if (cameraFile != null && cameraFile.exists()) {
                String picturePath = cameraFile.getAbsolutePath();
                LonLat ll = SysUtils.getInstance().getLL();
                Utils.writeLatLonIntoJpeg(picturePath, ll.GetLat(), ll.GetLon());
//                setResult(RESULT_OK, new Intent().putExtra(RESULT_PICTURE_PATH, picturePath));
                initData();
            }
        }

    }

    private void onToEdit() {
        if (picFilelist.size() < 1) {
            showShortToast(getString(R.string.swtpksc));
            return;
        }
        mIsEdit = true;
        findViewById(R.id.ctrl_pic_edit).setVisibility(View.VISIBLE);
        selectAll(false);
    }

    private File cameraFile;

    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!CommonUtil.isExitsSdcard()) {
            showShortToast("SD卡不存在，不能拍照");
            return;
        }

        String dirPath = Environment.getExternalStorageDirectory() + "/DCIM";
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定调用相机拍照后照片的储存路径
        cameraFile = new File(dirPath, "photo" + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        toActivity(intent, REQUEST_CODE_CAMERA);
    }

    int _select = 0;

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    public class GridAdapter extends BaseAdapter<Entry<Integer, String>> {
        private final String TAG = "GridAdapter";

        public GridAdapter(Activity context) {
            this(context, R.layout.pic_grid_item);
        }

        public GridAdapter(Activity context, int layoutRes) {
            super(context);
            setLayoutRes(layoutRes);
        }

        private int layoutRes;//item视图资源

        public void setLayoutRes(int layoutRes) {
            this.layoutRes = layoutRes;
        }

        private boolean hasName = false;//是否显示名字

        public GridAdapter setHasName(boolean hasName) {
            this.hasName = hasName;
            return this;
        }

        private boolean hasCheck = true;//是否使用标记功能

        public GridAdapter setHasCheck(boolean hasCheck) {
            this.hasCheck = hasCheck;
            return this;
        }

        public boolean getItemChecked(int position) {
            if (hasCheck == false) {
                Log.e(TAG, "<<< !!! hasCheck == false  >>>>> ");
                return false;
            }
            return hashMap.get(position);
        }

        public void setItemChecked(int position, boolean isChecked) {
            if (hasCheck == false) {
                Log.e(TAG, "<<< !!! hasCheck == false >>>>> ");
                return;
            }
            hashMap.put(position, isChecked);
            notifyDataSetChanged();
        }
        //item标记功能，不需要可以删除>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


        public int selectedCount = 0;

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        layoutRes, parent, false);
            }

            ImageView iv_item = BaseViewHolder.get(convertView, R.id.iv_item);
            TextView tv_focus = BaseViewHolder.get(convertView, R.id.tv_focus);

            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            iv_check.setTypeface(AppContext.getInstances().getIconfont());

            final Entry<Integer, String> kvb = getItem(position);
            int gridIndex = kvb.getKey();

            if (gridIndex >= picFilelist.size()) {
                return convertView;
            }
            String path = picFilelist.get(gridIndex);
            ImageLoaderUtil.loadImage(iv_item, path);

            int select = lvPhoneGird.getSelectedItemPosition();
            if (select == position && SysUtils.getInstance().is240x320) {
                tv_focus.setVisibility(View.VISIBLE);
            } else {
                tv_focus.setVisibility(View.GONE);
            }

            if (mIsEdit) {
                boolean ischeck = getItemChecked(position);
                if (ischeck) {
                    iv_check.setText(R.string.fonticon_xz);
                } else {
                    iv_check.setText(R.string.fonticon_wxz);
                }
                iv_check.setVisibility(View.VISIBLE);
            } else {
                iv_check.setVisibility(View.GONE);
            }


            return convertView;
        }

        /**
         * 刷新列表
         *
         * @param list
         */
        @Override
        public synchronized void refresh(List<Entry<Integer, String>> list) {
            if (list != null) {
                initList(list);
                selectedCount = 0;
                for (int i = 0; i < this.list.size(); i++) {
                    if (getItemChecked(i) == true) {
                        selectedCount++;
                    }
                }
            }
            notifyDataSetChanged();
        }

        /**
         * 标记List<String>中的值是否已被选中。
         * 不需要可以删除，但“this.list = list;”这句
         * 要放到constructor【这个adapter只有ModleAdapter(Context context, List<Object> list)这一个constructor】里去
         *
         * @param list
         * @return
         */
        @SuppressLint("UseSparseArrays")
        private void initList(List<Entry<Integer, String>> list) {
            this.list = list;
            if (hasCheck) {
                hashMap = new HashMap<Integer, Boolean>();
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        hashMap.put(i, false);
                    }
                }
            }
        }

    }

    private List<String> picFilelist = new ArrayList<String>();

    String EXDIR0 = Start.RUNDIR + "/HCMap_EX/image/";
    String EXDIR1 = "/mnt/sdcard2/BHCMapper/HCMap_EX/image/";

    private void seachPic(String path) {
        File fRoot = new File(path);
        File[] files = fRoot.listFiles();
        if (files == null)
            return;

        for (int j = 0; j < files.length; j++) {
            String fName = files[j].getName();
            if (files[j].isDirectory()) {
                seachPic(files[j].getPath());
            } else {
                if (fName.contains(".jpg") || fName.contains(".jpeg") || fName.contains(".png")) {
                    picFilelist.add(files[j].getPath());
                }
            }
        }
    }

    private HashMap<Integer, Boolean> hashMap;

    public void onSelectAll(View v) {
        selectAll(true);
    }

    public void onSelectAllNO(View v) {
        selectAll(false);
    }

    public void selectAll(boolean isSelected) {
        if (hashMap == null) {
            hashMap = new HashMap<Integer, Boolean>();
        }
        hashMap.clear();
        if (picFilelist != null) {
            for (int i = 0; i < picFilelist.size(); i++) {
                hashMap.put(i, isSelected);
            }
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

        if (isSelected) {
            bt_pic_do.setText(getString(R.string.delete));
        } else {
            bt_pic_do.setText(getString(R.string.cancel));
        }

    }

    boolean mIsEdit = false;

    public void onDelSelected(View v) {
        boolean haveselected = false;
        for (int i = 0; i < picFilelist.size(); i++) {
            if (hashMap.get(i)) {
                haveselected = true;
                break;
            }
        }

        if (haveselected) {
            new AlertDialog(context, getString(R.string.wxts), "确定删除选择的图片？", true, 0, this).show();
        } else {
            mIsEdit = false;
            findViewById(R.id.ctrl_pic_edit).setVisibility(View.GONE);

            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }

    }

    private void delSelected() {
        mIsEdit = false;
        findViewById(R.id.ctrl_pic_edit).setVisibility(View.GONE);
        showShortToast(getString(R.string.deleteok));

        List<String> dellist = new ArrayList<String>();

        for (int i = 0; i < picFilelist.size(); i++) {
            if (hashMap.get(i)) {
                dellist.add(picFilelist.get(i));
            }
        }

        boolean isDel = false;
        for (int i = 0; i < dellist.size(); i++) {
            File file = new File(dellist.get(i));
            // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    isDel = true;
                }
            }
        }

        if (isDel) {
            initData();
        }

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 0) {
            delSelected();
        }
    }
}
